package net.connector;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 方法类。建立Socket客户端，完成“调用-返回”式通信
 * 
 * @author Bai Yu
 *
 */
public class SocketClient {
	public SocketClient(String serverIp, int serverPort) {
		this.ip = serverIp;
		this.port = serverPort;

		connected = false;
	}

	/**
	 * 连接到服务端<br>
	 * 如果正常连接，则打开调用流和返回流，并占用相应资源。之后允许下列操作：<br>
	 * 1.获取已建立的调用流、返回流<br>
	 * 2.关闭连接并释放资源<br>
	 * 如果连接失败，则不占用任何资源
	 * 
	 * @throws UnknownHostException
	 *             无法解析ip地址
	 * @throws IOException
	 *             建立连接失败
	 */
	public void connect() throws UnknownHostException, IOException {
		try {
			server = new Socket(ip, port);
		} catch (IOException e) {
			connected = false;
			throw e;
		}

		try {
			callStream = server.getOutputStream();
			returnStream = server.getInputStream();
		} catch (IOException e) {
			connected = false;
			try {
				server.close();
			} catch (IOException close) {
			}
			throw e;
		}

		connected = true;
	}

	public String getDisplayName() {
		return ip + ":" + port;
	}

	public boolean connected() {
		return connected;
	}

	/**
	 * 获取已创建的调用流
	 */
	public OutputStream getCallStream() {
		return callStream;
	}

	/**
	 * 获取已创建的返回流
	 */
	public InputStream getReturnStream() {
		return returnStream;
	}

	/**
	 * 关闭连接并释放资源
	 */
	public void close() {
		try {
			server.close();
		} catch (IOException e) {
		}
	}

	private Socket server;
	private OutputStream callStream;
	private InputStream returnStream;

	private String ip;
	private int port;

	private boolean connected;
}
